import time
from threading import Thread

import requests

from ws_server import send_message

# 房间号
room = ''
flag = False

# 弹幕url
url = 'https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory'
# 请求头
headers = {
    'authority': 'api.live.bilibili.com',
    'accept': 'application/json,text/plain,*/*',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.50'
}


def set_flag(value):
    global flag
    flag = value


def set_room(value):
    global room
    room = value

#  重发机制
def Reissued():
    # 定义POST传递的参数
    data = {
        'roomid': room
    }
    wait_time = 1  # 重试间隔时间（秒）

    while True:
        try:
            # 获取直播间弹幕
            response = requests.post(url=url, headers=headers, data=data)
            response.raise_for_status()  # 检查响应状态码，如果不是200，会抛出异常
            return response  # 发送成功，返回响应结果
        except requests.exceptions.RequestException as e:
            print(f"错误原因: {str(e)}")
            print(f"等待 {wait_time} 秒...")
            time.sleep(wait_time)


def get_danmu(datalist):
    global flag
    html = Reissued()
    if html is not None:
        html_data = html.json()
        # print("-----------------------------------")
        # 解析弹幕列表
        for content in html_data['data']['room']:
            # 获取昵称
            nickname = content['nickname']
            # 获取发言
            text = content['text']
            # 获取用户UID
            uid = content['uid']
            # 获取timeline
            timeline = content['timeline']
            dict_data = {
                'Id': uid,
                'Nickname': nickname,
                'Content': text,
                'timeline': timeline
            }
            # 检查新字典是否存在于列表字典中
            if not any(
                    d['Id'] == uid and d['Content'] == text and d['Nickname'] == nickname for d
                    in datalist):
                datalist.append(dict_data)
                if flag:
                    send_message(dict_data)
        if not flag:
            flag = True
        if len(datalist) > 20:
            datalist = datalist[-20:]
            return datalist
        else:
            return datalist


def start():
    thread = Thread(target=run)
    thread.start()


def run():
    datalist = []
    while True:
        # 暂停0.5防止CPU占用过高
        time.sleep(1)
        # 获取弹幕
        datalist = get_danmu(datalist)
